<?php

/**
 * Class UserController
 */
class UserController extends Controller_Base
{
    public function init()
    {
        parent::init();
        SmartyAdapter::assign('type', Module_InfoBase_MediationOrgan::$type);
        $this->workerId =  Module_User_Administrator::getInstance()->getWorkerd(1);
        $this->workerId2 =  Module_User_Administrator::getInstance()->getWorkerd(2);
    }

    /**
     * 用户列表
     */
    public function indexAction()
    {
        $request = $this->getRequest();
        $name = $request->getQuery('name', '');
        $workerId = intval($request->getQuery('workerId', 0));
        $mediationOrganId = intval($request->getQuery('mediationOrganId', 0));
        $mobile = intval($request->getQuery('mobile', 0));

        $pn = intval($this->getRequest()->getQuery('page', 1));

        $limit = 10;
        // where
        $query['limit'] = $limit;
        $query['name'] = $name;
        $query['workerId'] = $workerId;
        $query['mediationOrganId'] = $mediationOrganId;
        $query['mobile'] = $mobile;
        $where = $this->getWhere('id');
        array_push($where,"role_id <> 1");
        if($name){
            array_push($where,"name = '{$name}'");
        }
        if($workerId){
            array_push($where,"(workerId = '{$workerId}' or workerId2 = '{$workerId}')");
        }
        if($mediationOrganId){
            array_push($where,"mediationOrganId = '{$mediationOrganId}'");
        }
        if($mobile){
            array_push($where,"mobile = '{$mobile}'");
        }
        $pn = $pn ? $pn : 1;
        $pageSize = $limit;
        $start = ($pn - 1) * $pageSize;
        $total = Module_User_Administrator::getInstance()->getAllBySearch(['count(id) as total'], ['where' => $where]);
        $total = $total[0]['total'];
        //计算分页
        $totalPage = ceil($total / $pageSize);
        if ($pn > $totalPage && $totalPage > 0) {
            $this->redirect('/user/index?page=' . $totalPage);
            exit;
        }

        $list = Module_User_Administrator::getInstance()->getAllBySearch(['*'], array('where' => $where, 'start' => $start, 'order' => 'id DESC', 'limit' => $limit));

        $roleArr = Module_User_Role::getInstance()->getListAll();
        $roles = [];
        if ($roleArr) {
            foreach ($roleArr as $key => $role) {
                $roles[$role['id']] = $role['title'];
            }
        }
        if ($list && is_array($list)) {
            foreach ($list as $key => $val) {
                $list[$key]['num'] = strlen($val['id']) >= 4 ? $val['id'] : str_pad($val['id'], 4, '0', STR_PAD_LEFT);
            }
        }
        $data = [];

        //赋值调解部门
        $this ->getMediationOrgan();


        $statusArr = Module_User_Administrator::$statusArr;
        SmartyAdapter::assign('statusArr', $statusArr);
        SmartyAdapter::assign('list', $list);
        SmartyAdapter::assign('roles', $roles);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('firm', $data);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $pageSize);
        SmartyAdapter::assign('curPageNum', $pn);
        SmartyAdapter::assign('page_query', http_build_query($query));
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::$templateName = 'user/index';
    }

    /**
     * 删除用户
     */
    public function delAction()
    {
        $actionData = array(
            'source_type' => '1',
            'action_type' => '5',
            'action_time' => time(),
            'action_uid' =>$this->admin['id'],
            'action_uname' => $this->admin['name'],
            'mobile' => $this->admin['mobile'],
            'action_group' => $this->admin['role_id'],
            'action_des' => '删除用户',
            'action_res' => '1',
            'action_main' => 'user',
            'action_event' => 'editPassword',
        );
        $request = $this->getRequest();
        $id = intval($request->getPost('id'));
        if (!$id) {
            AjaxTool::returnJsonData(4001, Setup_Error::getConfig(4001), []);
        }
        $admin = Module_User_Administrator::getInstance()->getAdminById($id);
        if (!$admin) {
            $actionData['action_des'] =  '删除用户失败';
            $actionData['action_res'] =  0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(4005, Setup_Error::getConfig(4005), []);
        }
        if ($admin['workerId']) {
            $actionData['action_des'] =  '删除用户失败';
            $actionData['action_res'] =  0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(5006, '该用户名下还有坐席，请解绑坐席后再删除', []);
        }
        if ($admin['status'] != 2) {
            $actionData['action_des'] =  '删除用户失败';
            $actionData['action_res'] =  0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(5006, Setup_Error::getConfig(5006), []);
        }
        $cases = Module_Mediate_Case::getInstance()->getOne(['id'],["mediatorId={$id}",'sysStatus = 1']);
        if($cases){
            $actionData['action_des'] =  '删除用户失败';
            $actionData['action_res'] =  0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(5006, '该用户名下还有未处理案件，请将案件转走后再删除', []);
        }
        $delRes = Module_User_Administrator::getInstance()->deleteById($id);
        if (!$delRes) {
            $actionData['action_des'] =  '删除用户失败';
            $actionData['action_res'] =  0;
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
        }
        @Module_Uaction_Hook::onActionData($actionData);
        AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), []);
    }

    /**
     * 添加用户
     */
    public function addAction()
    {
        SmartyAdapter::$templateName = 'user/add';
        $request = $this->getRequest();
        $userInfo = $request->getPost('data');
        $roleArr = Module_User_Role::getInstance()->getAllBySearch(['*'],['where'=>["id <>1"]]);
        $roleGroup = [];
        $file = $request->getFiles('file','');

        if ($roleArr && is_array($roleArr)) {
            foreach ($roleArr as $k => $val) {
                $provisioning = Module_User_Provisioning::getInstance()->getAllBySearch(["controller"], ["where" => ["id in ({$val['provisioning']})"]]);
                $provisioning_controller = array_column($provisioning,'controller');
                $roleGroup[$val['id']] = $provisioning_controller;
            }


        }
        $dataBase = Module_User_Administrator::getInstance()->getAllBySearch(['workerId'],['where'=>["(workerId <> 0 or workerId2 <> 0)","status =1"]]);
        $statusArr = Module_User_Administrator::$statusArr;
        $jobNumArr = array_diff($this->workerId,array_column($dataBase,'workerId'));
        array_multisort($jobNumArr);
        $jobNumArr2 = array_diff($this->workerId2,array_column($dataBase,'workerId'));
        array_multisort($jobNumArr2);
        $workerNum = Module_Mediate_Workernumber::getInstance()->getAllBySearch(['workerId','displayName'], ["where" => ["isDel=1"]]);
        $skillGroup = array_column($workerNum,'displayName','workerId');

        if (!empty($userInfo)) {
            parse_str(urldecode($userInfo),$userInfo);
            $userInfo = $userInfo['user'];
            $actionData = array(
                'source_type' => '1',
                'action_type' => '1',
                'action_time' => time(),
                'action_uid' =>$this->admin['id'],
                'action_uname' => $this->admin['name'],
                'mobile' => $this->admin['mobile'],
                'action_group' => $this->admin['role_id'],
                'action_des' => '添加用户成功',
                'action_res' => '1',
                'action_main' => 'user',
                'action_event' => 'add',
            );
            foreach ($userInfo as $key => $value) {
                if(is_string($value)){
                    $userInfo[$key] = trim($value);
                }
            }
            if (!$userInfo['name']) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5000, Setup_Error::getConfig(5000), []);
            }
            if (!$userInfo['mobile']) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5001, Setup_Error::getConfig(5001), []);
            }
            if (!$userInfo['mediationOrganId']) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, '必须选择所属调解部门', []);
            }
            if (!Validator::Validate($userInfo['mobile'], 'mobile')) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5002, Setup_Error::getConfig(5002), []);
            }
            if (!in_array($userInfo['role_id'], array_column($roleArr, 'id'))) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5003, Setup_Error::getConfig(6003), []);
            }

            if (!in_array($userInfo['status'], array_keys($statusArr))) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5004, Setup_Error::getConfig(5004), []);
            }

            if ($userInfo['dataType'] == 4 && empty($userInfo['allowOrganId'])) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, '自定义数据权限，需要选择可查看部门', []);
            }
            if($userInfo['dataType'] == 4){
                $userInfo['allowOrganId'] = implode(',',$userInfo['allowOrganId']);
            }else{
                $userInfo['allowOrganId'] ='';
            }
//            if (isset($roleGroup[$userInfo['role_id']]) && (in_array('incoming', $roleGroup[$userInfo['role_id']]) || in_array('caseAdjust', $roleGroup[$userInfo['role_id']]))) {
//                if ((!$userInfo['workerId'] ) ) {
//                    $actionData['action_des'] =  '添加用户失败';
//                    $actionData['action_res'] =  0;
//                    @Module_Uaction_Hook::onActionData($actionData);
//                    AjaxTool::returnJsonData(5019, Setup_Error::getConfig(5019), []);
//                }
//            }
//            if (!in_array('incoming', $roleGroup[$userInfo['role_id']]) && !in_array('caseAdjust', $roleGroup[$userInfo['role_id']])) {
//                $userInfo['workerId'] = 0;
//            }
            if ($userInfo['status'] == 2) {
                $userInfo['workerId'] = 0;
                $userInfo['workerId2'] = 0;
            }
            if ($userInfo['workerId']) {
                if (!in_array($userInfo['workerId'], $this->workerId)) {
                    $actionData['action_des'] =  '添加用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5014, Setup_Error::getConfig(5014), []);
                }
                $jobAdmin = Module_User_Administrator::getInstance()->getByJobNumber($userInfo['workerId']);
                if ($jobAdmin) {
                    $actionData['action_des'] =  '添加用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5016, Setup_Error::getConfig(5016), []);
                }
            }
            if ($userInfo['workerId2']) {
                if (!in_array($userInfo['workerId2'], $this->workerId2)) {
                    $actionData['action_des'] =  '添加用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5014, Setup_Error::getConfig(5014), []);
                }
                $jobAdmin = Module_User_Administrator::getInstance()->getByJobNumber($userInfo['workerId2']);
                if ($jobAdmin) {
                    $actionData['action_des'] =  '添加用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5016, Setup_Error::getConfig(5016), []);
                }
            }


            $mobileAdmin = Module_User_Administrator::getInstance()->getByMobile($userInfo['mobile']);
            if ($mobileAdmin) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5005, Setup_Error::getConfig(5005), []);
            }

            //添加的用户使用随机密码
//            $pw = $this->random_char(8);
            $pw = "PWD123456";
            $time = time();
            $password = Module_User_Administrator::encodePassword($pw, $time);

            $avatarImg = '';
            if(!empty($file)){
                if ($file['error'] != 4) {
                    $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'mediators',0,md5($userInfo['mobile']));
                    if (!$uploadFile || $uploadFile['code']) {
                        AjaxTool::returnJsonData(400, "上传失败");
                    }
                    $avatarImg = $uploadFile['data'];
                }
            }
            $saveData = [
                'name' => addslashes($userInfo['name']),
                'mobile' => $userInfo['mobile'],
                'password' => $password,
                'register_time' => $time,
                'status' => $userInfo['status'],
                'workerId' => $userInfo['workerId'],
                'workerId2' => $userInfo['workerId2'],
                'showWorkerId' => empty($userInfo['showWorkerId']) ? ($userInfo['workerId'] ? $userInfo['workerId'] : $userInfo['workerId2']) : $userInfo['showWorkerId'],
                'role_id' => intval($userInfo['role_id']),
                'mediationOrganId' => intval($userInfo['mediationOrganId']),
                'dataType' => intval($userInfo['dataType']),
                'allowOrganId' => $userInfo['allowOrganId'],
                'avatarImg' => $avatarImg,
            ];


            $retId = Module_User_Administrator::getInstance()->insertData($saveData);
            if (!$retId) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
            }
            if(!empty($userInfo['workerId'])){
                $worker = [
                    'workerId' => $userInfo['workerId'],
                    'mediatorId' => $retId,
                    'mediator' => addslashes($userInfo['name']),
                    'mediationOrganId' =>  intval($userInfo['mediationOrganId']),
                ];
                Module_Mediate_Workernumber::getInstance()->singleUpdate($worker, 'workerId');
            }
            if(!empty($userInfo['workerId2'])){
                $worker = [
                    'workerId' => $userInfo['workerId2'],
                    'mediatorId' => $retId,
                    'mediator' => addslashes($userInfo['name']),
                    'mediationOrganId' =>  intval($userInfo['mediationOrganId']),
                ];
                Module_Mediate_Workernumber::getInstance()->singleUpdate($worker, 'workerId');
            }
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), ['pwd' => $pw]);
        }

        //赋值调解部门
        $this ->getMediationOrgan();
        SmartyAdapter::assign('roleArr', $roleArr);
        SmartyAdapter::assign('statusArr', $statusArr);
        SmartyAdapter::assign('jobNumArr', $jobNumArr);
        SmartyAdapter::assign('jobNumArr2', $jobNumArr2);
        SmartyAdapter::assign('skillGroup', $skillGroup);

    }

    /**
     * 编辑用户
     */
    public function editAction()
    {
        header("content-type:text/html;charset=utf-8;");
        SmartyAdapter::$templateName = 'user/edit';
        $request = $this->getRequest();
        $id = intval($request->getQuery('id'));
        $userInfo = $request->getPost('data');

        if(!empty($userInfo)){
            parse_str(urldecode($userInfo),$userInfo);
            $id = $userInfo['id'];
            $userInfo = $userInfo['user'];
        }
        $file = $request->getFiles('file','');
        $admin = Module_User_Administrator::getInstance()->getAdminById($id);
        if (empty($id) || !$admin) {
            echo '<script>alert("错误的参数");window.location.href="/user/index";</script>';
            die;
        }
        $roleArr = Module_User_Role::getInstance()->getAllBySearch(['*'],['where'=>["id <>1"]]);
        // $roleMapArr = Module_User_RoleGroupMap::getInstance()->getAllList();
        $roleGroup = [];
//        if ($roleMapArr && is_array($roleMapArr)) {
//            foreach ($roleMapArr as $key => $value) {
//                $roleGroup[$value['role_id']][] = $value['controller'];
//            }
//        }
        if ($roleArr && is_array($roleArr)) {
            foreach ($roleArr as $k => $val) {
                $provisioning = Module_User_Provisioning::getInstance()->getAllBySearch(["controller"], ["where" => ["id in ({$val['provisioning']})"]]);
                $provisioning_controller = array_column($provisioning,'controller');
                $roleGroup[$val['id']] = $provisioning_controller;
            }


        }
        $dataBase = Module_User_Administrator::getInstance()->getAllBySearch(['workerId,workerId2'],['where'=>["(workerId <> 0 or workerId2 <> 0)","status =1","id <> {$id}"]]);
        $statusArr = Module_User_Administrator::$statusArr;
        $jobNumArr = array_diff($this->workerId,array_column($dataBase,'workerId'));
        array_multisort($jobNumArr);
        $jobNumArr2 = array_diff($this->workerId2,array_column($dataBase,'workerId2'));
        array_multisort($jobNumArr2);
        $workerNum = Module_Mediate_Workernumber::getInstance()->getAllBySearch(['workerId','displayName'], ["where" => ["isDel=1"]]);
        $skillGroup = array_column($workerNum,'displayName','workerId');


        if (!empty($userInfo)) {
            $actionData = array(
                'source_type' => '1',
                'action_type' => '2',
                'action_time' => time(),
                'action_uid' =>$this->admin['id'],
                'action_uname' => $this->admin['name'],
                'mobile' => $this->admin['mobile'],
                'action_group' => $this->admin['role_id'],
                'action_des' => '编辑用户成功',
                'action_res' => '1',
                'action_main' => 'user',
                'action_event' => 'edit',
            );
            foreach ($userInfo as $key => $value) {
                if(is_string($value)){
                    $userInfo[$key] = trim($value);
                }
                if ($key == 'id') {
                    $userInfo[$key] = intval($value);
                }
            }
            if (!$userInfo['name']) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5000, Setup_Error::getConfig(5000), []);
            }
            if (!$userInfo['mobile']) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5001, Setup_Error::getConfig(5001), []);
            }
            if (!$userInfo['mediationOrganId']) {
                $actionData['action_des'] =  '添加用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, '必须选择所属调解部门', []);
            }
            if (!Validator::Validate($userInfo['mobile'], 'mobile')) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5002, Setup_Error::getConfig(5002), []);
            }
            if (!in_array($userInfo['role_id'], array_column($roleArr, 'id'))) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5003, Setup_Error::getConfig(5003), []);
            }
            if (!in_array($userInfo['status'], array_keys($statusArr))) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5004, Setup_Error::getConfig(5004), []);
            }
            if (!isset($userInfo['id']) || !$userInfo['id']) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, Setup_Error::getConfig(4001), []);
            }
//
            if ($userInfo['workerId']) {
                if (!in_array($userInfo['workerId'], $this->workerId)) {
                    $actionData['action_des'] =  '编辑用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5014, Setup_Error::getConfig(5014), []);
                }
                $jobAdmin = Module_User_Administrator::getInstance()->getByJobNumber($userInfo['workerId']);
                if ($jobAdmin && $jobAdmin['id'] != $userInfo['id']) {
                    $actionData['action_des'] =  '编辑用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5016, Setup_Error::getConfig(5016), []);
                }
            }
            if ($userInfo['workerId2']) {
                if (!in_array($userInfo['workerId2'], $this->workerId2)) {
                    $actionData['action_des'] =  '编辑用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5014, Setup_Error::getConfig(5014), []);
                }
                $jobAdmin = Module_User_Administrator::getInstance()->getByJobNumber($userInfo['workerId2']);
                if ($jobAdmin && $jobAdmin['id'] != $userInfo['id']) {
                    $actionData['action_des'] =  '编辑用户失败';
                    $actionData['action_res'] =  0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    AjaxTool::returnJsonData(5016, Setup_Error::getConfig(5016), []);
                }
            }
            if ($userInfo['dataType'] == 4 && empty($userInfo['allowOrganId'])) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, '自定义数据权限，需要选择可查看部门', []);
            }
            if($userInfo['dataType'] == 4){
                $userInfo['allowOrganId'] = implode(',',$userInfo['allowOrganId']);
            }else{
                $userInfo['allowOrganId'] ='';
            }
            $mobileAdmin = Module_User_Administrator::getInstance()->getByMobile($userInfo['mobile']);
            if ($mobileAdmin && $mobileAdmin['id'] != $userInfo['id']) {
                $actionData['action_des'] =  '编辑用户失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5005, Setup_Error::getConfig(5005), []);
            }
            if(!empty($file)){
                if ($file['error'] != 4) {
                    $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'mediators',0,md5($userInfo['mobile']));
                    if (!$uploadFile || $uploadFile['code']) {
                        AjaxTool::returnJsonData(400, "上传失败");
                    }
                    $userInfo['avatarImg'] = $uploadFile['data'];
                }
            }
            $updateRes = Module_User_Administrator::getInstance()->updateItemById($userInfo);
            if (!$updateRes) {
                $actionData['action_des'] = '编辑用户失败';
                $actionData['action_res'] = 0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
            }
            @Module_Uaction_Hook::onActionData($actionData);


            if(empty($userInfo['showWorkerId']) && !empty($userInfo['workerId'])){
                $userInfo['showWorkerId'] = $userInfo['workerId'];
            }

            if(!empty($userInfo['workerId'])){
                $worker = [
                    'workerId' => $userInfo['workerId'],
                    'mediatorId' => $admin['id'],
                    'mediator' => addslashes($userInfo['name']),
                    'mediationOrganId' =>  intval($userInfo['mediationOrganId']),
                ];
                Module_Mediate_Workernumber::getInstance()->singleUpdate($worker, 'workerId');
            }
            if(!empty($userInfo['workerId2'])){
                $worker = [
                    'workerId' => $userInfo['workerId2'],
                    'mediatorId' => $admin['id'],
                    'mediator' => addslashes($userInfo['name']),
                    'mediationOrganId' =>  intval($userInfo['mediationOrganId']),
                ];
                Module_Mediate_Workernumber::getInstance()->singleUpdate($worker, 'workerId');
            }
            //更新 workernumber
            if ($admin['workerId'] != $userInfo['workerId']) {
                //被换掉的  删除调解员信息
                if(!empty($admin['workerId'])){
                    $worker2 = [
                        'workerId' => $admin['workerId'],
                        'mediatorId' => '',
                        'mediator' => '',
                        'mediationOrganId' => '',
                    ];
                    Module_Mediate_Workernumber::getInstance()->singleUpdate($worker2, 'workerId');
                }
            }
            //更新 workernumber
            if ($admin['workerId2'] != $userInfo['workerId2']) {
                //被换掉的  删除调解员信息
                if(!empty($admin['workerId'])){
                    $worker2 = [
                        'workerId' => $admin['workerId2'],
                        'mediatorId' => '',
                        'mediator' => '',
                        'mediationOrganId' => '',
                    ];
                    Module_Mediate_Workernumber::getInstance()->singleUpdate($worker2, 'workerId');
                }
            }
            AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), []);
        }

        $this->getMediationOrgan();
        $admin['allowOrganId'] = explode(',',$admin['allowOrganId']);
        SmartyAdapter::assign('roleArr', $roleArr);
        SmartyAdapter::assign('adminUser', $admin);
        SmartyAdapter::assign('statusArr', $statusArr);
        SmartyAdapter::assign('jobNumArr', $jobNumArr);
        SmartyAdapter::assign('jobNumArr2', $jobNumArr2);
        SmartyAdapter::assign('skillGroup', $skillGroup);

    }

    public function resetPWDAction(){
        $request = $this->getRequest();
        $id = intval($request->getPost('id'));
        if (!$id) {
            AjaxTool::returnJsonData(4001, Setup_Error::getConfig(4001), []);
        }
        $admin = Module_User_Administrator::getInstance()->getAdminById($id);
        if (!$admin) {
            AjaxTool::returnJsonData(4005, '操作失败找不到用户', []);
        }
        $password = Module_User_Administrator::encodePassword("PWD123456", $admin['register_time']);
        Module_User_Administrator::getInstance()->singleUpdate(['id'=>$id,'password'=>$password]);
        AjaxTool::returnJsonData(200, '操作成功', []);

    }



    function random_char($length = 8, $chars = null)
    {
        if (empty($chars)) {
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&^*=';
        }
        $chars = str_shuffle($chars);
        return substr($chars, 0, $length);
    }

    public function make_password($length = 8)
    {
        // 密码字符集，可任意添加你需要的字符  
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '@', '!', '@', '#', '$', '%', '^', '&', '*');
        // 在 $chars 中随机取 $length 个数组元素键名  
        $keys = array_rand($chars, $length);
        $password = "";
        for ($i = 0; $i < $length; $i++) {
            // 将 $length 个数组元素连接成字符串
            $password .= $chars[$keys[$i]];
        }
        return $password;
    }

    //修改密码
    public function editPasswordAction()
    {
        $actionData = array(
            'source_type' => '1',
            'action_type' => '3',
            'action_time' => time(),
            'action_uid' =>$this->admin['id'],
            'action_uname' => $this->admin['name'],
            'mobile' => $this->admin['mobile'],
            'action_group' => $this->admin['role_id'],
            'action_des' => '修改密码',
            'action_res' => '1',
            'action_main' => 'user',
            'action_event' => 'editPassword',
        );
        SmartyAdapter::$templateName = 'user/edit_password';
        $request = $this->getRequest();
        $userInfo = $request->getPost('user');
        if ($userInfo) {
            foreach ($userInfo as $key => $value) {
                $userInfo[$key] = trim($value);
                if ($key == 'id') {
                    $userInfo[$key] = intval($value);
                }
            }
            // 判断参数
            if (!$userInfo['originalPassword']) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5007, Setup_Error::getConfig(5007), []);
            }
            if (!$userInfo['newPassword']) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5008, Setup_Error::getConfig(5008), []);
            }
            if (!$userInfo['newPassword2']) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5012, Setup_Error::getConfig(5012), []);
            }
            if (!$userInfo['id']) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4001, Setup_Error::getConfig(4001), []);
            }
            if (strlen($userInfo['newPassword']) < 8) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5009, Setup_Error::getConfig(5009), []);
            }
            if (!preg_match('/((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))^.{1,}$/', $userInfo['newPassword'])) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5010, Setup_Error::getConfig(5010), []);
            }
            if ($userInfo['newPassword'] != $userInfo['newPassword2']) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5013, Setup_Error::getConfig(5013), []);
            }
            $admin = Module_User_Administrator::getInstance()->getAdminById($userInfo['id']);
            if (!$admin) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4005, Setup_Error::getConfig(4005), []);
            }
            // 判断旧密码
            $md5Password = Module_User_Administrator::encodePassword($userInfo['originalPassword'], $admin['register_time']);
            if ($md5Password != $admin['password']) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(5011, Setup_Error::getConfig(5011), []);
            }
            $pwd = Module_User_Administrator::encodePassword($userInfo['newPassword'], $admin['register_time']);
            $updateRes = Module_User_Administrator::getInstance()->updatePwdById($admin['id'], $pwd);
            if (!$updateRes) {
                $actionData['action_des'] =  '修改密码失败';
                $actionData['action_res'] =  0;
                @Module_Uaction_Hook::onActionData($actionData);
                AjaxTool::returnJsonData(4000, Setup_Error::getConfig(4000), []);
            }
            @Module_Uaction_Hook::onActionData($actionData);
            AjaxTool::returnJsonData(200, Setup_Error::getConfig(200), []);
        }
    }
}